package cn.xxstudy.blog.dao

import cn.xxstudy.blog.entity.Blog
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.transaction.annotation.Transactional


/**
 * 作者：wuxinxi on 2020/11/25
 * 包名：cn.xxstudy.blog.dao
 * TODO:博客数据管理
 */
interface BlogRepository : JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {

    fun deleteBlogById(id: Long): Int

    @Query("select b from Blog b where b.published = true")
    fun findTop(pageable: Pageable): List<Blog>

    @Query("select b from Blog b where ( b.title like ?1 or b.content like ?1) and b.published = true")
    fun findByQuery(query: String, pageable: Pageable): Page<Blog>

    @Transactional
    @Modifying
    @Query("update Blog b set b.lookCount = b.lookCount+1 where b.id = ?1")
    fun updateLookCount(id: Long?): Int

    @Query("select function('date_format',b.updateDateTime,'%Y') as year from Blog b  where b.published = true  group by function('date_format',b.updateDateTime,'%Y') order by year desc ")
    fun findGroupYear(): List<String>

    @Query("select b from Blog b where b.published = true and function('date_format',b.updateDateTime,'%Y') = ?1 ")
    fun findByYear(year: String): List<Blog>
}